package com.anhtuan.reminder;

import java.util.ArrayList;
import java.util.List;

import com.anhtuan.reminder.R;
import com.anhtuan.reminder.listelement.BaseListElement;
import com.anhtuan.reminder.listelement.ClearTaskListElement;
import com.anhtuan.reminder.listelement.NewTaskListElement;
import com.anhtuan.reminder.providers.TaskItem;
import com.anhtuan.reminder.providers.TasksProviderWrapper;
import com.anhtuan.reminder.services.ScheduleClient;
import com.anhtuan.reminder.ultils.ListAdapter;
import com.anhtuan.reminder.ultils.Ultils;

import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.ListView;

public class MainActivity extends FragmentActivity {

	public static final String TASK_ID_KEY = "TaskID";

	private ListView lv_option_list;
	private ListView lv_selection_list;

	private List<BaseListElement> listOptions;
	private List<BaseListElement> listElements;
	
	private ScheduleClient scheduleClient = null;
		
	public int getListElementsSize() {
		return listElements.size();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		initComponent(savedInstanceState);
		
		// Load tasks from database
		getAllTaskFromDB();
		
		// Start schedule service
		scheduleClient.doBindService();
		
	}
	
	@Override
	protected void onResume() {
		super.onResume();
	}
	
	@Override
	protected void onStop() {
		super.onStop();
		
		// Stop schedule service
		if (scheduleClient != null) {
			scheduleClient.doUnbindService();
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == Activity.RESULT_OK) {
			if (data != null) {
				
				Uri result = data.getData();
				
				if (result.equals(SelectionActivity.NEW_ACTION)) {
					
					listOptions.get(requestCode).onActivityResult(data);
					
				} else if (result.equals(SelectionActivity.EDIT_ACTION )) {
					
					listElements.get(requestCode).onActivityResult(data);
					
				} else if (result.equals(SelectionActivity.DELETE_ACTION)) {
					
					int taskId = data.getExtras().getInt(TASK_ID_KEY);
					
					stopScheduleATask(taskId);
					removeTaskById(taskId);
				}
			}
		}
	}

	private void initComponent(Bundle savedInstanceState) {

		// Find list view
		lv_option_list = (ListView) findViewById(R.id.option_list);
		lv_selection_list = (ListView) findViewById(R.id.selection_list);
		lv_selection_list.setVisibility(View.INVISIBLE);
		
		// Set up list view
		listOptions = new ArrayList<BaseListElement>();
		listElements = new ArrayList<BaseListElement>();

		// Add an item for the NewTask
		listOptions.add(new NewTaskListElement(this, listOptions.size()));
		listOptions.add(new ClearTaskListElement(this, listOptions.size()));
		lv_option_list.setAdapter(new ListAdapter(
				getApplication(), R.id.option_list, listOptions));
		
		// Initiate service clients
		scheduleClient = new ScheduleClient(this);
	}

	// Schedule alarm
	public void startScheduleATask(TaskItem taskItem) {
		scheduleClient.startScheduleATask(taskItem.getId(), taskItem.getRepeat(), taskItem.getDay(), taskItem.getFirstContent());
	}
	
	public void stopScheduleATask(int taskId) {
		scheduleClient.stopScheduleATask(taskId);
	}
	
	public void stopScheduleAllTask() {
		for (int i = 0; i < listElements.size(); i++) {
			stopScheduleATask(Integer.parseInt(listElements.get(i).getTag().toString()));
		}
	}
	
	// Get all task from database
	public void getAllTaskFromDB() {
		LoadTasks loadTask = new LoadTasks(this);
		loadTask.execute();
	}
	
	// Add a task to list elements
	public void addTask(BaseListElement element) {

		if (lv_selection_list.getVisibility() == View.INVISIBLE) {
			lv_selection_list.setVisibility(View.VISIBLE);
		}

		listElements.add(element);
		// Set the list view adapter
		lv_selection_list.setAdapter(new ListAdapter(
				getApplication(), R.id.selection_list, listElements));
	}
	
	// Update task at [position] in list elements
	public void updateTaskItem(int position, TaskItem taskItem) {

		BaseListElement element = null;

		element = Ultils.convertToBaseListElement(this, taskItem, position);
		
		if (element != null) {
			listElements.set(position, element);
		}
		
		// Set the list view adapter
		lv_selection_list.setAdapter(new com.anhtuan.reminder.ultils.ListAdapter(
				getApplication(), R.id.selection_list, listElements));
	}
	
	public void removeTaskById(int id) {
		
		// Remove from GUI
		for (int i = 0; i < listElements.size(); i++) {
			if (Integer.parseInt(listElements.get(i).getTag().toString()) == id) {
				listElements.remove(i);
				break;
			}
		}
		
		resetElementRequestcode();
		
		// Set the list view adapter
		lv_selection_list.setAdapter(new com.anhtuan.reminder.ultils.ListAdapter(
				getApplication(), R.id.selection_list, listElements));
		
		// Hide list view if have not any element
		if (listElements.size() == 0) {
			lv_selection_list.setVisibility(View.INVISIBLE);
		}
	}
	
	public void removeAllTask() {
		
		// Remove from GUI
		listElements.clear();
		
		// Set the list view adapter
		lv_selection_list.setAdapter(new com.anhtuan.reminder.ultils.ListAdapter(
				getApplication(), R.id.selection_list, listElements));
		
		// Hide list view
		lv_selection_list.setVisibility(View.INVISIBLE);
	}
	
	// Reset request code of each element in list elements
	private void resetElementRequestcode() {
		for (int i = 0; i < listElements.size(); i++) {
			listElements.get(i).setRequestCode(i);
		}
	}
		
	private class LoadTasks extends AsyncTask<Void, Integer, Void> {
		private ProgressDialog progressDialog;
		private List<BaseListElement> listElements;
		
		public LoadTasks(Context context) {
			progressDialog = new ProgressDialog(context);
			this.listElements = new ArrayList<BaseListElement>();
		}
		
		@Override
		protected void onPreExecute() {
			progressDialog.setMessage(getResources().getString(R.string.progress_dialog_loading_text));
			progressDialog.show();
		}
		
		@Override
		protected void onPostExecute(Void result) {
			if (progressDialog.isShowing()) {
				
				try {
					Thread.sleep(50);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				
				progressDialog.dismiss();
			}
		}
		
		@Override
		protected Void doInBackground(Void... params) {
			
			// Get all tasks from database
			List<TaskItem> taskItems = TasksProviderWrapper.getAllTasks(getContentResolver());
			
			for (int i = 0; i < taskItems.size(); i++) {
				
				BaseListElement element = null;
				
				element = Ultils.convertToBaseListElement(MainActivity.this, taskItems.get(i), i);
				
				if (element != null) {
					this.listElements.add(element);
					
					// Update GUI
					publishProgress(i);
				}
			}
			
			return null;
		}
		
		@Override
		protected void onProgressUpdate(Integer... values) {
			addTask(this.listElements.get(values[0]));
		}
	}
}
